import 'package:flutter/material.dart';

import 'dart:io';
import 'package:heven/pages/music/widget/index.dart';
import 'package:heven/api/index.dart';
import 'package:heven/utils/index.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';

import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:share_plus/share_plus.dart';

class MusicPage extends StatefulWidget {
  const MusicPage({super.key});

  @override
  _MusicPageState createState() => _MusicPageState();
}

class _MusicPageState extends State<MusicPage> {
  bool _isDownloading = false; // 用于标记是否正在下载
  double _downloadProgress = 0.0; // 下载进度
  bool _songDeleted = false;

  @override
  void initState() {
    super.initState();
  }

  Future<void> _shareMusicToWeChat(String songTitle, String songUrl) async {
    try {
      final box = context.findRenderObject() as RenderBox?;

      print(songUrl);

      await Share.shareUri(
        Uri.parse(songUrl),
        sharePositionOrigin: box!.localToGlobal(Offset.zero) & box.size,
      );
      Navigator.pop(context, _songDeleted);
      print("微信分享成功");
    } catch (e) {
      print("微信分享失败: $e");
    }
  }

  Future<void> _downloadMusic(String songTitle, String songUrl) async {
    Navigator.pop(context);
    // 先请求存储权限
    final status = await Permission.storage.request();

    if (!status.isGranted) {
      Fluttertoast.showToast(msg: "请授予存储权限以下载文件");
      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(content: Text("请授予存储权限以下载文件")),
      // );
      return;
    }

    setState(() {
      _isDownloading = true;
      _downloadProgress = 0.0;
    });

    try {
      Directory? directory;
      if (Platform.isAndroid) {
        directory = await getExternalStorageDirectory();
      } else if (Platform.isIOS) {
        directory = await getApplicationDocumentsDirectory();
      }

      if (directory == null) {
        setState(() {
          _isDownloading = false;
          _downloadProgress = 0.0;
        });
        Fluttertoast.showToast(msg: "无法获取存储路径");

        return;
      }

      final filePath = "${directory.path}/$songTitle.mp3";

      Dio dio = Dio();
      await dio.download(
        songUrl,
        filePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {
            setState(() {
              _downloadProgress = received / total;
            });
          }
        },
      );

      setState(() {
        _isDownloading = false;
        _downloadProgress = 0.0;
      });
      Fluttertoast.showToast(msg: "下载成功，文件已保存到: $filePath");
      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(content: Text("下载成功，文件已保存到: $filePath")),
      // );
    } catch (e) {
      setState(() {
        _isDownloading = false;
        _downloadProgress = 0.0;
      });
      Fluttertoast.showToast(msg: "下载失败: $e");
      // ScaffoldMessenger.of(context).showSnackBar(
      //   SnackBar(content: Text("下载失败: $e")),
      // );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 50.0,
        leadingWidth: 28.5,
        leading: GestureDetector(
          child: Padding(
            padding: const EdgeInsets.only(left: 10),
            child: Image.asset(
              'assets/images/return.png',
              width: 18.5,
              height: 17.5,
            ),
          ),
          onTap: () {
            Navigator.pop(context, _songDeleted);
          },
        ),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 15),
            child: GestureDetector(
              onTap: () => {_showBottomSheet(context)},
              child: Image.asset(
                'assets/images/share_icon.png',
                width: 30,
                height: 30,
              ),
            ),
          ),
        ],
      ),
      body: Container(
        child: MusicPlayer(),
      ),
    );
  }

  void _showBottomSheet(BuildContext context) {
    final musicState = context.read<MusicState>();
    final currentSong = musicState.currentSong;
    final songTitle = currentSong?['title'] ?? "未知歌曲";
    final songUrl = currentSong?['audio_url'] ?? "";
    final type = musicState.type;

    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 150,
          decoration: const BoxDecoration(
            color: Color(0xFF323851),
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(27.0),
              topRight: Radius.circular(27.0),
            ),
          ),
          child: Column(
            children: [
              Align(
                alignment: Alignment.topRight,
                child: IconButton(
                  icon: Icon(Icons.close),
                  color: Colors.white,
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ),
              Padding(
                padding: EdgeInsets.only(left: 68.0, right: 68.0, top: 10),
                child: Row(
                  mainAxisAlignment: type == 3
                      ? MainAxisAlignment.spaceBetween
                      : MainAxisAlignment.center,
                  children: [
                    _buildButton('assets/images/share.png', "分享作品", () {
                      _shareMusicToWeChat(songTitle, songUrl);
                    }),
                    // _buildButton('assets/images/download.png', "下载作品", () {
                    //   _downloadMusic(songTitle, songUrl);
                    // }),
                    if (type == 3)
                      _buildButton('assets/images/delete.png', "删除作品",
                          () async {
                        final uid = await Common.getStorageValue('uid');
                        final songId = currentSong?['id'];
                        final result =
                            await delmusic({"id": songId, "uid": uid});
                        if (result.isNotEmpty) {
                          musicState.deleteCurrentSong();
                          _songDeleted = true;
                          Navigator.pop(context);
                        }
                        print(result);
                      }),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

Widget _buildButton(String url, String label, VoidCallback onTap) {
  return GestureDetector(
    onTap: onTap,
    child: Column(
      children: [
        CircleAvatar(
          backgroundColor: Colors.grey[300],
          radius: 20.0,
          child: Image.asset(url),
        ),
        const SizedBox(height: 7.0),
        Text(
          label,
          style:
              const TextStyle(color: Colors.white, fontSize: 11, height: 1.5),
        ),
      ],
    ),
  );
}
